import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:get/get_state_manager/src/rx_flutter/rx_ticket_provider_mixin.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';
import '../entity/new_product_nav_entity.dart';

///新品榜单 控制器
class NewProductsRankingCtr extends BaseController with SingleGetTickerProviderMixin {
  // 背景图
  String newRankings = '';

  TabController? tabController;

  final ScrollController scrollController = ScrollController();

  List<NewProductNavEntity> itemList = [];

  //商品列表
  List goodsList = [];
  //当前选中的活动
  int selected = 0;

  int nowDoing = 0;

  //拼团样式类型
  int style = 2;

  //当前页码
  int page = 1;

  Map bargainingDetail = {};

  //是否有下一页
  bool hasNextPage = true;

  @override
  Future<void> onInit() async {
    await getDefaultInfoConfig();
    await getActivityNewProductNavigationInfo();
    tabController = TabController(length: itemList.length, vsync: this);
    // 添加监听
    tabController?.addListener(() {
      baseRefreshCtr.refreshCompleted(resetFooterState: true);
      scrollToTopSmooth();
      selected = tabController!.index;
      page = 1;
      onPageRefresh();
    });
    super.onInit();

    UmengCommonSdk.onPageStart('新品榜单');
  }

  Future getDefaultInfoConfig() async {
    await Network.getDefaultInfo().then((value) {
      newRankings = value['newRankings'];
      print('newRankings === $newRankings');
      update();
    }).catchError((error) {
      print('value === $error');
    });
  }

  //获取活动时间列表
  Future getActivityNewProductNavigationInfo() async {
    Tools.showLoading();
    await Network.getActivityNewProductNavigation().then((value) {
      itemList = value
          .map((item) {
            try {
              return NewProductNavEntity.fromJson(item);
            } catch (e) {
              return null; // 转换失败时返回 null
            }
          })
          .where((item) => item != null)
          .cast<NewProductNavEntity>()
          .toList();
      update();
      onPageRefresh();
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  //获取团购商品列表
  Future specialGoodsList() async {
    Tools.showLoading();
    Network.getSpecialGoodsList({"marketingId": itemList[selected].value, "sid": AppData.sid, "pageNum": page, "pageSize": 10}).then((value) {
      hasNextPage = value['hasNextPage'];
      if (page > 1) {
        goodsList.addAll(value['list']);
      } else {
        goodsList = value['list'];
      }
      Tools.hideLoading();
      update();
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  //选择活动

  /*
  void change(int index) {
    selected = index;

    page = 1;

    itemList.forEach((element) {
      element.type = 0;
    });

    if (index == 0) {
      itemList[index + 1].type = 1;
    }

    if (index > 0 && index < (itemList.length)) {
      itemList[index - 1].type = 2;
      if (index < itemList.length - 1) {
        itemList[index + 1].type = 1;
      }
    }

    getBargainingGoodsList();
    update();
  }

   */
  @override
  void onPageRefresh() async {
    super.onPageRefresh();
    await specialGoodsList();
    // 完成下拉刷新，并重置 footer 状态
    // baseRefreshCtr.refreshCompleted(resetFooterState: !hasNextPage);
    baseRefreshCtr.refreshCompleted(resetFooterState: true);
    // 根据是否有更多数据来设置 footer 的状态
    if (hasNextPage) {
      baseRefreshCtr.resetNoData(); // 重置为上拉加载状态
    } else {
      baseRefreshCtr.loadNoData(); // 显示 "没有更多数据"
    }
  }

  @override
  void onPageLoading() async {
    super.onPageLoading();
    if (hasNextPage) {
      page += 1;
      await specialGoodsList();
      baseRefreshCtr.loadComplete();
    } else {
      baseRefreshCtr.loadNoData();
    }
  }

  @override
  void onClose() {
    tabController?.dispose();
    scrollController.dispose();
    super.onClose();
    UmengCommonSdk.onPageEnd('新品榜单');
  }

  // 平滑滚动到顶部
  void scrollToTopSmooth() {
    scrollController.animateTo(
      0.0, // 滚动到顶部的位置
      duration: const Duration(milliseconds: 300), // 动画持续时间
      curve: Curves.easeInOut, // 滚动曲线
    );
  }
}
